LastNViewLoader = null;
NotificationManager = null;
UserManager = null;

_UserManager = function() {
    this.IsIdentivied = true;
 }
_UserManager.prototype = {
	Identify: function(){
		if(!AuthManager.Identify())
		{
			if(!NavigationManager.PageIsGrantedForAnonymusNavigation(NavigationManager.GetCurrentTarget()))
			{
				NavigationManager.GoTo("auth");
			}
			else
            {
                 CloakManager.OffCloak(true,true);
            }
            this.IsIdentivied = false;
		}
		return this.IsIdentivied;
	},
	Verify: function(login, password) {
		if(ValidationController.CreateAndAddValidationItemToStack(login, isNullOrEmpty).ValidateAndCleanStack().Result)
		{
			var nItem = NotificationManager.CreateNotification("Login is empty. Please enter login", ["error"]);
			NotificationManager.ShowMessages([nItem]);
			return;
		}
		if(ValidationController.CreateAndAddValidationItemToStack(password, isNullOrEmpty).ValidateAndCleanStack().Result)
		{
			var nItem = NotificationManager.CreateNotification("Password is empty. Please enter password", ["error"]);
			NotificationManager.ShowMessages([nItem]);
			return;
		}
		CloakManager.OnCloak(false,true);
		var _AuthentificateUser = ClientCommandsManager.Get("AuthentificateUser");
		_AuthentificateUser.Login = login;
		_AuthentificateUser.Password = $.md5(password);
		_AuthentificateUser.Sender = NavigationManager.GetCurrentTarget();
	    ClientCommandsManager.Execute(_AuthentificateUser, this.SuccessHandler, null);
	},
    SuccessHandler: function(data, status, request) {
    	CloakManager.OffCloak(true,true);
    	if(data && data.RCode > -1)
    	{
    		UserManager.SetUserCookie(data);
    		NavigationManager.GoTo("general");
    	}
    	else
    	{
    		var nItem = NotificationManager.CreateNotification("Login or Password incorrect", ["error"]);
    		var nItem2 = NotificationManager.CreateNotification("If you are not registered please register first <a title=\"Registartion\" href=\"#\" onclick=\"NavigationManager.GoTo('reg');\">here</a>", ["info"], 10000);
    		NotificationManager.ShowMessages([nItem, nItem2]);
    	}
    },
    SetUserCookie: function(data){
		$.cookie("sessionId", data.SessionID);
		$.cookie("fName", data.FrendlyName);
		$.cookie("uId", data.Id);
    },
    DeleteUserCookie: function(){
    	$.cookie("sessionId", null);
		$.cookie("fName", null);
		$.cookie("uId", null);
    },
	SetUserData: function(){
		if(this.Identify()){
			$(".userName").text($.cookie("fName"));
		}
	},
	ExitUser: function(){
		/*var answer = confirm ("You really want to quit?");
		if (answer)
			{*/
				this.DeleteUserCookie();
				NavigationManager.GoTo("auth");
			//}
	}
}
_LastNViewLoader = function() { }
_LastNViewLoader.prototype = {
    Load: function() {
        var _GetLastNView = ClientCommandsManager.Get("GetLastNView");
        ClientCommandsManager.Execute(_GetLastNView, this.SuccessHandler, this.ErrorHandler);
    },
    SuccessHandler: function(data, status, request) {
        var jqoView = $(".LastNViewContainer .View");

        for (var key in data) {
            var view = new _View();
            view.CreateView(data[key].ImageId, data[key].Title, data[key].Author, data[key].Rating).ParseToObj($(jqoView[key]));
        }
    },
    ErrorHandler: function(request, status, errortrow) {
    	ClientCommandsManager.DefaultErrorHandler(request, status, errortrow);
    }
}

_View = function() { }
_View.prototype = {
    Src: "",
    Title: "",
    Author: "",
    Rating: "",

    CreateView: function(src, title, author, rating) {
        this.Src = src;
        this.Title = title;
        this.Author = author;
        this.Rating = rating;
        return this;
    },

    ParseToObj: function(jqoView) {
        jqoView.find(".ViewImage").attr("src", "Handlers/ImageHandler.ashx?Id=" + this.Src);
        jqoView.find(".DescriptionMoto:first").html(this.Title);
        jqoView.find(".DescriptionAuthor:first").html(this.Author);
        jqoView.find(".DescriptionRating:first").html(this.Rating);
    }
}


_WeatherLoader = function() { } 
_WeatherLoader.prototype = {
    Load: function() {
        var _GetWeather = ClientCommandsManager.Get("GetWeather");
        ClientCommandsManager.Execute(_GetWeather, this.SuccessHandler, this.ErrorHandler);
    },
    SuccessHandler: function(data, status, request) {
        if (typeof (data) != "undefined") {
            $(".WeatherImage").attr("src", data.img_path);
            $(".WeatherTemp").html(data.temp_c + " C&deg;");
        }
    },
    ErrorHandler: function(request, status, errortrow) {
    	ClientCommandsManager.DefaultErrorHandler(request, status, errortrow);
    }
}


_NotificationManager = function() { 
    this.MessageStack = [];
    this._raisedIntervals = [];
}
_NotificationManager.prototype = {
	CreateNotification: function(message, cssClasses, autoHideInterval){
		var item = {};
			item.Message = message;
			item.CssClasses = cssClasses;
			item.AutoHideInterval = autoHideInterval;
		return item;
	},
	ShowMessages: function(messages){
        this.MessageStack = messages;
        var jqoNItem = $("#NotificationContainer .NotificationItem");
        if(jqoNItem.length>0)
        {
        	jqoNItem.slideUp("slow", function(){$("#NotificationContainer").hide(); NotificationManager.ConstructLayout();});
        }
        else
        {
            $("#NotificationContainer").hide();
            this.ConstructLayout();
        }
	},
    ConstructLayout: function(){
    	NotificationManager._clearRaisedIntervals();
        if (NotificationManager.MessageStack && NotificationManager.MessageStack.length>0) {
                var _html = "";
                for (var i=0, ic=NotificationManager.MessageStack.length; i<ic; i++) {
                    _html += "<div class='NotificationItem " + 
                    NotificationManager.MessageStack[i].CssClasses.join(' ')  +"' id='message_id_" + i + "'>" + 
                    NotificationManager.MessageStack[i].Message + 
                    "<div id='rightContainer'>" +
                    (NotificationManager.MessageStack[i].AutoHideInterval ? "<div id='time_place_message'>This message will be closed automaticly after <span id='timer_place'>" + 
                    		NotificationManager.MessageStack[i].AutoHideInterval/1000 + "</span> seconds</div>" : "") +
                    "<div id='closeNotificationItem' onclick=NotificationManager.CloseNotificationItem(" + i + ");>&nbsp;</div></div></div>";
                }
                if(NotificationManager.MessageStack.length > 1)
                	_html += "<div id='closeAllNotificationItems' onclick=NotificationManager.CloseAllNotifications();>close all</div>";
                $("#NotificationContainer").html(_html).slideDown("slow");
                NotificationManager.RaiseAutoTimeoutInterval();
            }
    },
    RaiseAutoTimeoutInterval: function(){
    	for (var i=0, ic=NotificationManager.MessageStack.length; i<ic; i++) {
            if(NotificationManager.MessageStack[i].AutoHideInterval){
            	NotificationManager._raiseElement(i, NotificationManager.MessageStack[i].AutoHideInterval/1000);
            }
    	}
    },
    _raiseElement: function(id, start_timer_position){
    	var timer = start_timer_position;
    	
    	var timer_on_ui_id = setInterval(function(){
	    		if(timer <= 0){
	                clearInterval(timer_on_ui_id);
	                NotificationManager._raisedIntervals[id] = null;
	            }
    			timer--;
    			NotificationManager._refreshNotificationItemTimer(id, timer)
    		}, 1000);
    	NotificationManager._raisedIntervals.push(timer_on_ui_id);
    	
    	var id_interval = setTimeout(function(){
                NotificationManager.CloseNotificationItem(id);
            }, NotificationManager.MessageStack[id].AutoHideInterval);
    	
    	NotificationManager._raisedIntervals.push(id_interval);
    },
    _clearRaisedIntervals: function(){
    	for (var i=0, ic=NotificationManager._raisedIntervals.length; i<ic; i++) {
    		clearInterval(NotificationManager._raisedIntervals[i]);
    	}
    	NotificationManager._raisedIntervals = [];
    },
    _refreshNotificationItemTimer: function(id, timerVal){
    	$("#message_id_" + id + " #timer_place").text(timerVal);
    },
	CloseNotificationItem: function(id){
		$("#message_id_" + id).slideUp("slow");
		this.MessageStack[id] = null;
		if(!this.VerifyMessageStack())
			$("#NotificationContainer #closeAllNotificationItems").slideUp("slow");
	},
	VerifyMessageStack: function(){
		var result = false;
		for(var i=0,ic=this.MessageStack.length; i<ic; i++){
			if(this.MessageStack[i] != null){
				result = true;
				break;
			}
		}
		return result;
	},
	CloseAllNotifications: function(){
		this.MessageStack = [];
		var jqoNItem = $("#NotificationContainer .NotificationItem, #NotificationContainer #closeAllNotificationItems");
        if(jqoNItem.length>0)
        	jqoNItem.slideUp("slow", function(){$("#NotificationContainer").html("").hide();});
	}
}

//_NotificationManager = function() { }
//_NotificationManager.prototype = {
//	RootId: -1,
//	GetMessagesById: function(rootId){
//		this.Root = rootId;
//		var _GetMessagesByUserId = ClientCommandsManager.Get("GetMessagesByUserId");
//		_GetMessagesByUserId.UserId = rootId;
//        ClientCommandsManager.Execute(_GetMessagesByUserId, this.SuccessHandler, this.ErrorHandler, true);
//	},
//    Listen: function() {
//        var _GetMessagesByUserId = ClientCommandsManager.Get("GetMessagesByUserId");
//        ClientCommandsManager.Execute(_GetMessagesByUserId, this.SuccessHandler, this.ErrorHandler, true);
//    },
//    SwitchAllMessage: function(length) {
//        var _height = 20;
//        if ($(".NotificationContainer").height() == _height && length > 1) {
//            _height = (length - 1) * _height;
//        }
//        $(".NotificationContainer").animate({ height: _height }, 'slow');
//    },
//    AddMessage: function(message){
//    	var _AddMessage = ClientCommandsManager.Get("AddMessage");
//    	_AddMessage.Message = message;
//    	ClientCommandsManager.Execute(_AddMessage, this.SuccessHandler, this.ErrorHandler, true);
//    },
//    SuccessHandler: function(data, status, request) {
//    	$(".NotificationContainer").html("");
//        if (data && data != "") {
//            var _html = "";
//            _html = _html + "<div class=\"NotificationMessageUIContainer\"><a class=\"NotificationShowAll\" href=# onclick=\"NotificationManager.SwitchAllMessage(" + data.length + ");\">" + ConstantsManager.Get("BodyNotificationCounter") + "</a>  <span class=\"NotificationMessageCounter\">" + data.length + "</span></div>";
//            var tree = _NotificationManager.prototype.ConstructTree(data);
//            var prevTreeNodePID = -1;
//            for (var i=0, ic=tree.length; i<ic; i++) {
//                _html += "<div class=\"NotificationItem\" id=\"node_id_" + tree[i].Id + "\">" + tree[i].Value + "</div>";
//            }
//            $(".NotificationContainer").html(_html).slideDown("slow");
//        }
//        //_NotificationManager.prototype.Listen();
//    },
//    ErrorHandler: function(request, status, errortrow) {
//    	ClientCommandsManager.DefaultErrorHandler(request, status, errortrow);
//    },
//    ConstructTree: function(data){
//    	var tree = [];
//    	for(var i=0, ic=data.length; i<ic; i++){
//    		if(data[i].ParentId == this.RootId)
//    		{
//    			tree.push(data[i]);
//    		}
//    		else
//    		{
//    			var found = false;
//    			for(var j=0, jc=tree.length; j<jc; j++)
//    			{
//    				found =	data[i].ParentId == tree[j].Id
//    				if(found)
//    				{
//    					tree.splice(j, 0, data[i]);
//    					break;
//    				}
//    			}
//    			if(!found)
//    				tree.push(data[i]);
//    		}
//    	}
//    	return tree.reverse();
//    }
//}